﻿using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	public static class EvalExtensions
	{
		public static void AddInformationMessage(this ViewDataDictionary viewData, string informationMessage, params object[] args)
		{
			AddInformationMessage(viewData, "__FORM", informationMessage, args);
		}

		public static void AddInformationMessage(this ViewDataDictionary viewData, string key, string informationMessage, params object[] args)
		{
			var informationMessages = viewData.GetValueOrDefault<InformationMessageDictionary>("__INFO");

			if (informationMessages == null)
			{
				informationMessages = new InformationMessageDictionary();
			}

			informationMessages.AddInformationMessage(key, informationMessage, args);

			viewData["__INFO"] = informationMessages;
		}

		public static object GetValueOrDefault(this ViewDataDictionary viewData, string key)
		{
			return viewData.GetValueOrDefault(key, null);
		}

		public static object GetValueOrDefault(this ViewDataDictionary viewData, string key, object defaultValue)
		{
			return viewData.Eval(key) ?? defaultValue;
		}

		public static T GetValueOrDefault<T>(this ViewDataDictionary viewData, string key)
		{
			return viewData.GetValueOrDefault(key, default(T));
		}

		public static T GetValueOrDefault<T>(this ViewDataDictionary viewData, string key, T defaultValue)
		{
			try
			{
				return (T)viewData.Eval(key);
			}
			catch
			{
				return defaultValue;
			}
		}

		public static bool HasInformationMessages(this ViewDataDictionary viewData)
		{
			return viewData.ContainsKey("__INFO");
		}
	}
}